<template>
    <div class="login-container">
        <div class="login-form-container">
            <h1>登录</h1>
            <el-form :model="loginForm" :rules="rules" ref="loginFormRef" label-width="100px" class="login-form">
                <el-form-item label="工号" prop="employeeNumber">
                    <el-input v-model="loginForm.employeeNumber"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="employeePassword">
                    <el-input type="password" v-model="loginForm.employeePassword"></el-input>
                </el-form-item>



                <el-form-item label="部门" prop="employeeDepartment">
                    <el-select v-model="loginForm.employeeDepartment" placeholder="请选择部门">
                        <el-option
                            v-for="department in departments"
                            :key="department.id"
                            :label="department.name"
                            :value="department.name"
                        ></el-option>
                    </el-select>
                </el-form-item>



                <el-form-item>
                    <el-button type="primary" @click="submitForm">登录</el-button>
                </el-form-item>
            </el-form>
        </div>
        <div class="background-image"></div>
    </div>
</template>

<script>
import {onMounted, reactive, ref} from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus'; // 引入 ElMessage
import service from "@/utils/request";

export default {
    // eslint-disable-next-line vue/multi-word-component-names
    name: 'Login',
    setup() {
        const router = useRouter();
        const loginForm = reactive({
            employeeNumber: '',
            employeePassword: '',
            employeeDepartment: ''
        });

        const rules = {
            employeeNumber: [
                { required: true, message: '请输入工号', trigger: 'blur' }
            ],
            employeePassword: [
                { required: true, message: '请输入密码', trigger: 'blur' }
            ],
            employeeDepartment: [
                { required: true, message: '请选择部门', trigger: 'change' }
            ]
        };

        const departments = ref([]); // 用于存储从后端获取的部门数据

        // 获取部门数据的方法
        const fetchDepartments = async () => {
            try {
                const response = await service.get('/role/listAll'); // 假设后端接口为 /role/listAll
                if (response.data.data && Array.isArray(response.data.data)) {
                    // 直接将后端返回的数据赋值给 departments
                    departments.value = response.data.data;
                    console.log('Fetched departments:', departments.value); // 检查数据
                } else {
                    console.error('Invalid department data format:', response.data);
                }
            } catch (error) {
                console.error('Failed to fetch departments:', error);
            }
        };

        const loginFormRef = ref(null);

        const submitForm = () => {
            if (loginFormRef.value) {
                loginFormRef.value.validate(async (valid) => {
                    if (valid) {
                        try {
                            const response = await service.post('/admin/employee/login', loginForm);
                            if (response.status === 200) {
                                // 登录成功，存储用户信息  localStorage 存储用户的登录状态
                                localStorage.setItem('isAuthenticated', true);
                                localStorage.setItem('employeeDepartment', response.data.employeeDepartment);
                                localStorage.setItem('employeeNumber', response.data.employeeNumber);
                                // localStorage.setItem('userPosition', response.data.position);
                                localStorage.setItem('userName', response.data.name);
                                localStorage.setItem('token',response.data.tokenMap.tokenHead+response.data.tokenMap.token)
                                console.log(response.data.tokenMap)

                                // 根据员工部门重定向到不同的页面
                                const employeeDepartment = response.data.employeeDepartment;
                                if (employeeDepartment === '超级管理员') {
                                    await router.push('/competitionManagement/list');
                                } else if (employeeDepartment === '科创部') {
                                    await router.push('/competitionManagement/listAddTeachers');
                                } else if (employeeDepartment === '学工处') {
                                    await router.push('/activityManagement/listAddTeachers');
                                }else
                                {
                                    await router.push('/competitionManagement/list');
                                }

                                ElMessage.success('登录成功'); // 使用 ElMessage 替代 this.$message
                            }
                        } catch (error) {
                            ElMessage.error('登录失败，请检查工号和密码');
                        }
                    } else {
                        console.log('error submit!!');
                        return false;
                    }
                });
            } else {
                console.error('Form reference is not initialized');
            }
        };
        onMounted(() => {

            fetchDepartments();

        });
        return {
            loginForm,
            rules,
            loginFormRef,
            departments,
            submitForm,
            fetchDepartments
        };
    }
};
</script>

<style scoped>
.login-container {
    display: flex;
    justify-content: flex-end; /* 调整为靠右对齐 */
    align-items: center;
    height: 100vh;
    position: relative; /* 设置为相对定位 */
    overflow: hidden; /* 隐藏溢出内容 */
}

.login-form-container {
    width: 500px;
    padding: 20px;
    background-color: rgba(255, 255, 255, 0.9);
    border-radius: 8px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    text-align: center;
    z-index: 1;
    margin-right: 200px;
}

h1 {
    font-size: 24px;
    margin-bottom: 20px;
    color: #333;
    font-weight: 600;
}

.login-form {
    display: flex;
    flex-direction: column;
}

.el-form-item {
    margin-bottom: 20px;
}

.el-button {
    background-color: #409eff;
    border-color: #409eff;
    color: #fff;
    font-size: 16px;
    border-radius: 4px;
    padding: 10px 20px;
    transition: background-color 0.3s, border-color 0.3s;
}

.el-button:hover {
    background-color: #66b1ff;
    border-color: #66b1ff;
}

.background-image {
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-image: url('@/assets/login.jpg');
    background-size: cover;
    background-position: center;
    z-index: 0;
    filter: blur(5px);
}
</style>
